<template>
  <div class="container">
    <navigate @answerBack="back" @rightClick="answerCardShow = !answerCardShow">
      测评答题
      <template v-slot:right>答题卡</template>
    </navigate>
    <van-overlay
      :show="showLoading"
      :z-index="1000"
      style="background-color: rgba(0, 0, 0, 0)"
    >
      <van-loading type="spinner" color="#1989fa" />
    </van-overlay>

    <!-- 答题卡 -->
    <div class="answerCard flex_column" v-if="answerCardShow">
      <div class="header flex_row flex_align_center between">
        <div class="title">答题情况：</div>
        <div class="flex_row flex_align_center">
          <div class="status flex_row flex_align_center yes">
            <div class="circle"></div>
            已作答
          </div>
          <div class="status flex_row flex_align_center no">
            <div class="circle"></div>
            未作答
          </div>
        </div>
      </div>
      <div class="main flex_row">
        <div
          :class="[
            'item',
            { over: item.user_answer_id },
            { current: currentQuestion == index + 1 },
          ]"
          v-for="(item, index) in answerList"
          @click="currentQuestion = index + 1"
          :key="index"
        >
          {{ index + 1 }}
        </div>
      </div>
      <div class="mask" @click="answerCardShow = false"></div>
    </div>

    <!-- 题目 -->
    <div class="question">
      <div class="title">{{ name }}</div>
      <!-- 进度 -->
      <div class="schedule">
        第{{ currentQuestion }}题/共{{ answerList.length }}题
      </div>
      <div class="line"></div>
      <!-- 问题 -->
      <div class="question" v-if="answerList[currentQuestion - 1]">
        {{ currentQuestion + "." + answerList[currentQuestion - 1].name }}
      </div>
      <div class="answer flex_column">
        <template v-if="answerList[currentQuestion - 1]">
          <div
            @click="selectQuestion(item)"
            :class="[
              'item',
              {
                current:
                  answerList[currentQuestion - 1].user_answer_id == item.id,
              },
            ]"
            v-for="(item, index) in answerList[currentQuestion - 1].answer"
            :key="index"
          >
            {{ item.name }}
          </div>
        </template>
      </div>
    </div>
    <button class="btn" @click="next(accomplish(answerList))">
      {{ accomplish(answerList) ? "提交答案" : "下一题" }}
    </button>
    <button class="prev" @click="prev">上一题</button>

    <!-- eachrt图标 -->

    <div
      ref="barChartssss"
      style="width: 600px; height: 300px"
      v-show="false"
    ></div>
    <div
      ref="gaugeChartssss"
      style="width: 360px; height: 360px"
      v-show="false"
    ></div>
  </div>
</template>

<script>
import axios from "axios";
import baseUrl from "@/server/baseUrl.js";
import * as echarts from "echarts";
import {
  queryRatingScaleQuestion,
  submitSelfAnswer,
  queryEvaluationTime,
  querySubscaleDet,
  submitTaskAnswer,
} from "@/api/evaluation/index";
import {
  subOfflineConsultResult,
  queryOffEvQuestions,
} from "@/api/consultation/record";
import {
  quereyConEvaProblem,
  subtOnlineConsultResult,
} from "@/api/consultation/online";
import { submitCourseEvaluationResult } from "@/api/funcation/psychologySchool";
import { subGroupActivityResult } from "@/api/funcation/groupActivity";
import { subTrainingLectureResult } from "@/api/funcation/training";
let prevRouterName = "";
const arr = [
  "home",
  "appointmentPreTask",
  "consultationRecordDetail",
  "appointmentRecordDetail",
];
export default {
  data() {
    return {
      sourceId: "",
      name: "",
      id: "",
      taskId: "",
      roleId: "",
      evaluationType: "",
      totalEvaluationTime: "", //总测评时间
      currentTime: "", //当前测评时间
      ratingScaleId: "", //量表id
      // 显示答题卡
      answerCardShow: false,
      // 答案列表
      answerList: [],
      // 量表名
      title: "",
      // 当前题目数
      currentQuestion: 1,
      // 总题数
      total: 0,
      // 开始时间
      startTime: 0,
      // 防止点击过快的锁
      lock: true,
      // 答题间隔的锁
      lock1: true,
      // 计时
      currentTime: 0,
      timer: null,
      // 测评时间
      minute: 0,
      // 测评设置
      setting: "",
      // 答题间隔
      readTime: 0,
      // 是否第二次选择最后一题
      overFlagNum: 0,

      sexOptions: [
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 2,
        },
      ],
      showLoading: false,
      ip: "", //域名
    };
  },
  created() {
    this.ip = this.$ip + "/";
    this.name = this.$route.query.name;
    this.taskId = this.$route.query.taskId;
    this.ratingScaleId = this.$route.query.ratingScaleId;
    this.roleId = this.$route.query.roleId;
    this.id = this.$route.query.id;
    this.evaluationType = this.$route.query.type;
    this.sourceId = this.$route.query.sourceId; //消息id,线下咨询传递过来的
    this.subType = this.$route.query.subType; //提交答案类型，线下咨询传递过来的
    this.taskUserId = this.$route.query.taskUserId; //历史记录传递字段
    this.taskType = this.$route.query.taskType; //前置后置任务类型
    this.getQuestion();

    this.overFlagNum = 0;

    this.getEvaluationTime();
  },
  methods: {
    async uploadImg(file) {
      try {
        let res = await this.postData(
          this.ip + "/common/upload/upload_base64_file",
          {
            file,
          }
        );
        if (res.code == 200) {
          return res.data;
        }
      } catch (e) {
        return "";
      } finally {
      }
    },

    juadgeGuage(name) {
      let res = name.replace(/\(|\)|\（|\）/g, "");
      return res == "症状自评量表SCL-90";
    },
    async postData(url, data) {
      const token = sessionStorage.getItem("token");
      const headers = {
        "Content-Type": "multipart/form-data",
      };

      if (token) {
        headers["token"] = token;
      }
      const response = await axios(url, {
        method: "POST",
        headers: headers,
        data:
          data instanceof FormData
            ? data
            : {
                ...data,
              },
      });
      return response.data;
    },
    barChart(report) {
      const columnarData = report.map((item, index) => {
        return item.score;
      });
      const data = report.map((item, index) => {
        return item.factor_name;
      });
      // x轴的名称需要的高度，由于斜度的关系，每个字的高度约8 实际10/2是5，由于下面没有高度，然后加5的一半
      let maxText = Math.max(...data.map((i) => i.length));
      let numY2 = 24 + maxText * 8;
      // Y轴的名称需要的宽度，由于需考虑（X轴的第一个名字、项目的最大数值）长度比较
      let maxScore = Math.max(...report.map((i) => i.score));
      let numX = 0; //10字体大小 13的字体大小
      if (data.length > 0) {
        numX = Math.max(data[0].length * 10, maxScore.toString().length * 13);
      }
      var chartDom = this.$refs.barChartssss;
      let myChart = echarts.getInstanceByDom(this.$refs.barChartssss);
      if (myChart == undefined) {
        myChart = echarts.init(chartDom);
      }
      var initOption = () => {
        let option = {
          animation: false,
          grid: {
            left: numX + 5,
            top: 35,
            bottom: numY2,
            right: 5,
          },
          xAxis: {
            type: "category",
            data: data,
            axisTick: { show: false },
            //设置坐标轴字体颜色和宽度
            axisLine: {
              //这是y轴文字颜色
              lineStyle: {
                color: "#8999AC",
              },
              show: true, //y轴线消失
            },
            axisLabel: {
              color: "#C2EFFF",
              fontSize: 10,
              rotate: 45,
            },
          },
          yAxis: {
            type: "value",
            //设置坐标轴字体颜色和宽度
            axisLine: {
              show: false, //y轴线消失
            },
            // 背景线变虚线
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: "#3D5676",
              },
            },
            axisLabel: {
              color: "#FFFFFF", //坐标值得具体的颜色
              fontSize: 13,
            },
          },
          series: [
            {
              data: columnarData,
              type: "bar",
              barWidth: 10,
              label: {
                show: true,
                color: "#C2EFFF",
                fontSize: 10,
                position: "top",
              },
              itemStyle: {
                //柱形图圆角，初始化效果
                borderRadius: [0, 0, 0, 0],
                color: function (params) {
                  let green = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#d3e1b6" },
                    { offset: 1, color: "#9bbb59" },
                  ]);
                  let red = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#e4b3b2" },
                    { offset: 1, color: "#c0504d" },
                  ]);
                  return report[params.dataIndex].is_warning != 1 ? green : red;
                },
              },
            },
          ],
        };
        option && myChart.setOption(option);
      };
      initOption();
      return myChart.getDataURL();
    },
    calculateTime(second, ping = 1, out = 1) {
      let hours = parseInt(parseInt(second / 60) / 60)
        .toString()
        .padStart(2, 0);
      let minute = (parseInt(second / 60) % 60).toString().padStart(2, 0);
      let sec = (parseInt(second) % 60).toString().padStart(2, 0);
      if (ping == 1) {
        if (out == 1) {
          return `${hours}:${minute}:${sec}`;
        } else {
          if (Number(hours) > 0) {
            return `${hours}:${minute}:${sec}`;
          }
          if (Number(minute) > 0) {
            return `${minute}:${sec}`;
          }
          return `${sec}`;
        }
      } else {
        if (out == 1) {
          return `${hours}时${minute}分${sec}秒`;
        } else {
          if (Number(hours) > 0) {
            return `${hours}时${minute}分${sec}秒`;
          }
          if (Number(minute) > 0) {
            return `${minute}分${sec}秒`;
          }
          return `${sec}秒`;
        }
      }
    },
    all_warning(FactorScore) {
      if (FactorScore) {
        let list = FactorScore.filter((i) => i.is_warning == 1).map(
          (i) => i.factor_name
        );
        return list.length > 0 ? list.join("、") : "--";
      } else {
        return "--";
      }
    },
    guageChart(score, high) {
      score = parseFloat(score);
      high = parseFloat(high);
      var chartDom = this.$refs.gaugeChartssss;
      if (!chartDom) {
        return;
      }
      var myChart = echarts.getInstanceByDom(this.$refs.gaugeChartssss);
      if (myChart == undefined) {
        myChart = echarts.init(chartDom);
      }
      let initOption = () => {
        let option = {
          animation: false,
          series: [
            {
              type: "gauge",
              center: ["50%", "50%"],
              radius: "95%",
              min: 0,
              max: high,
              axisLine: {
                lineStyle: {
                  width: 30,
                  color: [
                    [0.4, "#67e0e3"],
                    [0.8, "#37a2da"],
                    [1, "#fd666d"],
                  ],
                },
              },
              pointer: {
                itemStyle: {
                  color: "auto",
                },
              },
              pointer: {
                itemStyle: {
                  color: "auto",
                },
                length: "75%",
              },
              axisTick: {
                distance: -30,
                length: 8,
                lineStyle: {
                  color: "#12253b",
                  width: 2,
                },
              },
              splitLine: {
                distance: -30,
                length: 30,
                lineStyle: {
                  color: "#12253b",
                  width: 4,
                },
              },
              axisLabel: {
                color: "inherit",
                distance: 50,
                fontSize: 12,
              },
              detail: {
                valueAnimation: true,
                formatter: "{value}",
                color: "inherit",
                fontSize: 18,
              },
              data: [
                {
                  value: score,
                },
              ],
            },
          ],
        };

        option && myChart.setOption(option);
      };
      initOption();
      return myChart.getDataURL();
    },
    level_name(str) {
      return str.match(/\((.+?)\)|（[^）]+）/g)[0].slice(1, -1);
    },
    juadgeGuage(name) {
      let res = name.replace(/\(|\)|\（|\）/g, "");
      return res == "症状自评量表SCL-90";
    },
    filteringOfUniqueFields(
      array,
      findFieldValue,
      objectAttrOfArray,
      returnFieldName,
      defaultCharacters = "--"
    ) {
      let find = array.find((v) => v[objectAttrOfArray] == findFieldValue);
      return find ? find[returnFieldName] : defaultCharacters;
    },
    calcNum(i, list) {
      return i >= list.length - 2;
    },
    filterSexName(field) {
      return this.filteringOfUniqueFields(
        this.sexOptions,
        field,
        "value",
        "label"
      );
    },
    async getDetailToServe(type, api, id) {
      console.log(this.evaluationType, "llllll===");
      try {
        let result = await this.postData(this.ip + api, { id });
        let res = JSON.parse(result);
        if (res.code == 200) {
          let info;
          if (type == 2 || type == 5 || type == 4) {
            info = res.data;
          } else if (type == 1) {
            info = res.data.info;
          }
          let {
            SelfFactorScore,
            rating_scale_name,
            sex,
            finish_used_time,
            TaskFactorScore,
            ConsultOnlineFactorScore,
            ConsultOfflineFactorScore,
            TaskFactorScoreContinuity,
            ProxyFactorScore,
            ResultFactorScore,
          } = info;
          let FactorScore = {};
          let ping = "";
          if (type == 1) {
            FactorScore = SelfFactorScore;
            delete info.SelfFactorScore;
            ping = "SelfWord";
          }
          // 联评 2是任务 1是联评 数字拼接
          // 教职工联评 100是任务 1001是联评 数字拼接
          if (type == 2 || type == 100) {
            FactorScore = TaskFactorScore;
            delete info.TaskFactorScore;
            ping = "TaskWord";
          }
          if (type == 21 || type == 1001) {
            FactorScore = TaskFactorScoreContinuity;
            delete info.TaskFactorScoreContinuity;
            ping = "ContinuityWord";
          }
          if (type == 3) {
            FactorScore = ProxyFactorScore;
            delete info.ProxyFactorScore;
            ping = "ProxyWord";
          }
          if (type == 4) {
            FactorScore = ConsultOnlineFactorScore;
            delete info.ConsultOnlineFactorScore;
            ping = "ConsultOnlineWord";
          }
          if (type == 5) {
            FactorScore = ConsultOfflineFactorScore;
            delete info.ConsultOfflineFactorScore;
            ping = "ConsultOfflineWord";
          }
          if (type == 6) {
            FactorScore = ResultFactorScore;
            delete info.ResultFactorScore;
            ping = "GroupActivityWord";
          }
          let guage = {},
            line = [];
          if (FactorScore) {
            if (FactorScore.length === 1) {
              guage = FactorScore[0];
            }
            if (FactorScore.length !== 1) {
              if (this.juadgeGuage(rating_scale_name)) {
                guage = FactorScore[0];
                line = FactorScore.slice(1, -2);
              }
              if (!this.juadgeGuage(rating_scale_name)) {
                guage = FactorScore[0];
                line = FactorScore.slice(1);
              }
            }
          }
          let { score, rating_scale_factor_level } = guage;
          let high = guage.high_range;
          let guageChartReview = await this.uploadImg(
            this.guageChart(score, high)
          );
          let barChartReview = "";
          let barShow = line.length != 0;
          if (barShow) {
            barChartReview = await this.uploadImg(this.barChart(line));
          }
          if (FactorScore) {
            FactorScore.forEach((r, ri) => {
              r.factor_name_string =
                this.juadgeGuage(rating_scale_name) &&
                this.calcNum(ri, FactorScore)
                  ? ""
                  : "得分";
              r.score_string =
                this.juadgeGuage(rating_scale_name) &&
                this.calcNum(ri, FactorScore)
                  ? "项"
                  : "分";
              r.rating_scale_factor_level.forEach((j, ji) => {
                FactorScore[ri].rating_scale_factor_level[ji].level_name =
                  this.level_name(
                    FactorScore[ri].rating_scale_factor_level[ji].name
                  );
              });
            });
          }

          let result = Object.assign(info, {
            sex: this.filterSexName(sex),
            finish_used_time: this.calculateTime(finish_used_time),
            all_warning_string: this.all_warning(FactorScore),
            guageChartReview,
            barChartReview,
            FactorScore,
          });
          try {
            let response = await this.postData(
              this.ip +
                `/${
                  type == 100 || type == 1001 ? "workers" : "admin"
                }/Echarts/${ping}`,
              {
                data: JSON.stringify(result),
              }
            );
            let res = JSON.parse(response);
            if (res.code == 200) {
              this.showLoading = false;
              this.$toast.success("提交成功!");
              if (this.evaluationType == "taskEvaluation") {
                this.$router.push({
                  path: `/taskList?id=${this.taskId}`,
                });
              } else {
                this.$router.push("/nav/evaluate");
              }
              return true;
            }
          } catch (e) {
            return false;
          }
        }
      } catch (e) {
        return false;
      } finally {
      }
    },
    // 获取测评设置
    async getEvaluateSetting() {
      const params = {
        company_id: this.INFO.platform_unit_id,
      };
      const { data } = await apiEvaluateSetting(params);
      if (data.code == 200) {
        this.setting = data.data;
      }
    },
    // 上一题
    prev() {
      if (this.currentQuestion == 1)
        return this.$toast.fail("已经是最上面的一题了!");
      this.currentQuestion--;
    },
    sameOperate() {
      this.$toast.success("提交成功!");
      if (this.evaluationType == "taskEvaluation") {
        this.$router.push({
          path: `/taskList?id=${this.taskId}`,
        });
      } else {
        this.$router.push("/nav/evaluate");
      }
    },
    //提交测评答案
    async submitAnswer() {
      const userAnswerIds = this.answerList.map((item) => item.user_answer_id);
      // 线下咨询提交
      if (this.evaluationType === "offlineConsult") {
        let par = {
          source_id: this.sourceId, // 当前消息的id
          rating_scale_id: this.id, // 量表id
          question_answer: userAnswerIds,
          finish_used_time: this.currentTime,
        };
        let res = await subOfflineConsultResult(par);
        if (res.code == 200) {
          this.sameOperate()
          // let result_id = res.data.result_id;
          // this.getDetailToServe(
          //   5,
          //   "/user/consult/OfflineReportInfo",
          //   result_id
          // );
          // this.showLoading = true;
        }
      }
      // 自我测评提交
      else if (this.evaluationType === "selfEvaluation") {
        let par = {
          rating_scale_id: this.id,
          answer_role: "1",
          question_answer: userAnswerIds,
          finish_used_time: this.currentTime,
        };

        // 提交答案
        let res = await submitSelfAnswer(par);
        if (res.code == 200) {
          this.sameOperate()
          // let result_id = res.data.result_id;
          // this.getDetailToServe(
          //   1,
          //   "admin/task/selfEvaluationReportInfo",
          //   result_id
          // );
          // this.showLoading = true;
        }
      }
      // 任务测评提交（排除线上咨询情况）
      else if (this.evaluationType === "taskEvaluation") {
        let par = {
          task_id: this.taskId,
          task_user_id: this.id,
          rating_scale_id: this.ratingScaleId,
          answer_role: this.roleId,
          question_answer: userAnswerIds,
          finish_used_time: this.currentTime,
        };
        let res = await submitTaskAnswer(par);
        if (res.code == 200) {
          this.sameOperate()
          // let result_id = res.data.result_id;
          // // 得到详情信息
          // this.getDetailToServe(
          //   2,
          //   "user/Report/TaskEvaluationRightInfo",
          //   result_id
          // );
          // this.showLoading = true;
        }
      } else if (this.evaluationType === "onlineConsult") {
        let par = {
          source_id: this.sourceId,
          rating_scale_id: this.id,
          answer_role: this.roleId,
          question_answer: userAnswerIds,
          finish_used_time: this.currentTime,
        };
        let res = await subtOnlineConsultResult(par);
        if (res.code == 200) {
          // let result_id = res.data.result_id;
          // // 得到详情信息
          // this.getDetailToServe(4, "/user/consult/OnlineReportInfo", result_id);
          this.sameOperate()
          // this.showLoading = true;
        }
      } else if (this.evaluationType == "groupActivity") {
        let par = {
          task_id: this.taskId,
          task_user_id: this.taskUserId || 0, //只有历史才有
          rating_scale_id: this.id,
          question_answer: userAnswerIds,
          finish_used_time: this.currentTime,
        };
        let res = await subGroupActivityResult(par);
        if (res.code == 200) {
          this.$router.go(-1);
        }
      }
      //心理学堂
      else if (this.evaluationType == "psychologicalSchool") {
        let par = {
          id: this.id,
          question_answer: userAnswerIds,
          finish_used_time: this.currentTime,
        };
        await submitCourseEvaluationResult(par);
      }
      //培训讲座
      else if (this.evaluationType == "trainingLecture") {
        let par = {
          task_id: this.taskId,
          task_user_id: this.taskUserId || 0,
          rating_scale_id: this.id,
          type: this.taskType,
          question_answer: userAnswerIds,
          finish_used_time: this.currentTime,
        };
        let res = await subTrainingLectureResult(par);
        if (res.code == 200) {
          this.$router.go(-1);
        }
      }
    },
    // 下一题
    async next(type) {
      // 有type提交答案
      if (type) {
        let tipText;
        if (this.evaluationType == "selfEvaluation") {
          tipText = "（测评结果在测评中心--自我测评报告中查看）";
        } else if (this.evaluationType == "taskEvaluation") {
          tipText = "（测评结果在测评中心--任务测评报告中查看）";
        }

        this.$popup({
          visible: false,
          title: "提示",
          message: `<div>确定结束测评并提交答案吗？</div>
        ${
          (this.evaluationType === "selfEvaluation" ||
            this.evaluationType === "taskEvaluation") &&
          !arr.includes(prevRouterName)
            ? `<div style="white-space: nowrap;font-size: 14px;color: #959595;">${tipText}</div>`
            : ``
        }`,
          confirmOperate: () => {
            this.submitAnswer();
            clearInterval(this.timer);
          },
        });
        return;
      }
      if (!this.answerList[this.currentQuestion - 1].user_answer_id)
        return this.$toast.fail("请选择答案!");

      let over = this.answerList.every((item) => item.user_answer_id);
      if (!over && this.currentQuestion == this.answerList.length)
        return this.$toast.fail("还有题目没有答完!");
      if (this.currentQuestion == this.answerList.length)
        return this.$toast.fail("已经是最后一题了!");
      this.currentQuestion++;
    },

    // 选择题目
    selectQuestion(item) {
      if (this.lock && this.lock1) {
        this.lock = false;
        this.lock1 = false;
        setTimeout(() => {
          this.lock1 = true;
        }, this.readTime * 1000);
        this.$set(this.answerList[this.currentQuestion - 1], "id", item.id);
      }
    },
    sleepDelay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    },
    // 选择题目
    async selectQuestion(item) {
      this.$set(
        this.answerList[this.currentQuestion - 1],
        "user_answer_id",
        item.id
      );
      this.$set(
        this.answerList[this.currentQuestion - 1],
        "question_id",
        item.question_id
      );
      await this.sleepDelay(100)
      if(!this.accomplish(this.answerList) ) {
        this.next(this.accomplish(this.answerList))
      }
    },
    async getQuestion() {
      // psychologicalSchool
      // 自我测评、心理学堂
      if (
        this.evaluationType == "selfEvaluation" ||
        this.evaluationType == "psychologicalSchool" ||
        this.evaluationType == "groupActivity" ||
        this.evaluationType == "trainingLecture"
      ) {
        const res = await queryRatingScaleQuestion({ id: this.id });
        if (res.code == 200) {
          this.answerList = res.data;
        }
        // 任务测评
      } else if (this.evaluationType == "taskEvaluation") {
        const res = await querySubscaleDet({ id: this.id });
        if (res.code == 200) {
          this.answerList = res.data.question;
        }
        // 线下测评
      } else if (this.evaluationType == "offlineConsult") {
        const res = await queryOffEvQuestions({ id: this.id });
        if (res.code == 200) {
          this.answerList = res.data.question;
        }
        //线上测评
      } else if (this.evaluationType == "onlineConsult") {
        const res = await quereyConEvaProblem({ id: this.id });
        this.answerList = res.data.question;
      }
    },
    back() {
      this.$popup({
        visible: false,
        title: "提示",
        message: arr.includes(prevRouterName)
          ? "是否退出本次答题？"
          : "您确定中途退出吗？退出将不产生测评报告!",
        confirmOperate: () => {
          this.$router.go(-1);
        },
      });
    },
    async getEvaluationTime() {
      let res = await queryEvaluationTime({ id: this.ratingScaleId });
      this.totalEvaluationTime = res.data.time;
      if (this.totalEvaluationTime) {
        const startTime = Date.now();
        this.timer = setInterval(() => {
          let elapsedTime = Date.now() - startTime;
          this.currentTime = Math.floor(elapsedTime / 1000);
          const remainingTime = this.totalEvaluationTime - this.currentTime;
          if (remainingTime <= 0) {
            this.$toast.success("您的答题时间已用完！即将返回！");
            this.submitAnswer();
            clearInterval(this.timer); // 清除定时器
          }
        }, 1000);
      }
    },
  },
  computed: {
    // 判断题目是否做完
    accomplish() {
      return (answerList) => {
        return answerList.every((item) => item.user_answer_id);
      };
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },

  beforeRouteEnter(to, from, next) {
    prevRouterName = from.name;
    next();
  },
};
</script>

<style lang="less" scoped>
::v-deep .van-loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

@import "./css/index.less";
</style>
